import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login as loginApi, logout as logoutApi, getCurrentUser } from '@/api/auth'
import Cookies from 'js-cookie'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(Cookies.get('token') || '')
  const userInfo = ref(null)
  const permissions = ref([])

  // 登录
  const login = async (loginForm) => {
    /* // 模拟登录，暂时不调用真实接口
    if (loginForm.username === 'admin' && loginForm.password === '123456') {
      token.value = 'mock-admin-token'
      userInfo.value = {
        id: 1,
        employeeCode: 'EMP001',
        username: 'admin',
        realName: '系统管理员',
        gender: '男',
        phone: '010-88888888',
        email: 'admin@company.com',
        department: 'IT部',
        position: '系统管理员',
        role: 'admin',
        hireDate: '2024-01-01',
        isActive: 1,
        avatar: ''
      }
      permissions.value = ['*']
      Cookies.set('token', token.value, { expires: 7 })
      return Promise.resolve({ code: 200, message: '登录成功' })
    } else {
      return Promise.reject(new Error('用户名或密码错误'))
    } */
    
    
    // 【真实接口调用】 -  取消注释以使用真实API
    try {
      const response = await loginApi(loginForm)
      if (response.code === 200) {
        token.value = response.data.token
        userInfo.value = response.data.userInfo
        permissions.value = response.data.permissions || []
        
        // 存储token到cookie
        Cookies.set('token', token.value, { expires: 7 })
        
        return response
      }
    } catch (error) {
      throw error
    }
   
  }

  // 登出
  const logout = async () => {
    try {
      // 只有当token存在且有效时才发送登出请求
      if (token.value) {
        try {
          await logoutApi()
        } catch (error) {
          // 忽略登出请求的错误，避免循环调用
          console.error('登出请求失败:', error)
        }
      }
    } finally {
      // 清除状态
      token.value = ''
      userInfo.value = null
      permissions.value = []
      
      // 清除cookie
      Cookies.remove('token')
    }
  }

  // 获取当前用户信息
  const getUserInfo = async () => {
   /*  // 模拟获取用户信息
    if (token.value === 'mock-admin-token') {
      userInfo.value = {
        id: 1,
        employeeCode: 'EMP001',
        username: 'admin',
        realName: '系统管理员',
        gender: '男',
        phone: '010-88888888',
        email: 'admin@company.com',
        department: 'IT部',
        position: '系统管理员',
        role: 'admin',
        hireDate: '2024-01-01',
        isActive: 1,
        avatar: ''
      }
      permissions.value = ['*']
      return Promise.resolve({ code: 200, data: { userInfo: userInfo.value, permissions: permissions.value } })
    }

    return Promise.reject(new Error('无效的token')) */

    
    // 【真实接口调用】 - 取消注释以使用真实API
    try {
      const response = await getCurrentUser()
      if (response.code === 200) {
        userInfo.value = response.data.userInfo
        permissions.value = response.data.permissions || []
      }
      return response
    } catch (error) {
      throw error
    }
   
  }

  // 检查登录状态
  const checkLogin = async () => {
    if (token.value && !userInfo.value) {
      try {
        await getUserInfo()
      } catch (error) {
        // 获取用户信息失败，清除token
        logout()
      }
    }
  }

  // 检查权限
  const hasPermission = (permission) => {
    if (!permissions.value || permissions.value.length === 0) {
      return false
    }
    return permissions.value.includes(permission) || permissions.value.includes('*')
  }

  // 检查角色
  const hasRole = (role) => {
    if (!userInfo.value) {
      return false
    }
    return userInfo.value.role === role || userInfo.value.role === 'admin'
  }

  return {
    token,
    userInfo,
    permissions,
    login,
    logout,
    getUserInfo,
    checkLogin,
    hasPermission,
    hasRole
  }
}) 
 